package guutil

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"io/ioutil"
	"log"

	"gitee.com/MikeDDD/gu/logs"
)

func GzipCompress(source []byte) []byte {
	var buf bytes.Buffer

	gw := gzip.NewWriter(&buf)

	if _, err := gw.Write(source); err != nil {
		log.Println(err)
		return nil
	}
	if err := gw.Flush(); err != nil {
		log.Println(err)
		return nil
	}
	if err := gw.Close(); err != nil {
		log.Println(err)
		return nil
	}

	return buf.Bytes()
}

func GzipUncompress(source []byte) []byte {
	gr, err := gzip.NewReader(bytes.NewReader(source))
	if err != nil {
		log.Println(err)
		return nil
	}

	data, err := ioutil.ReadAll(gr)
	if err != nil {
		log.Println(err)
		return nil
	}

	return data
}

func GzipBase64Marshall(source []byte) (string, bool) {
	out := GzipCompress(source)
	if out == nil {
		return "", false
	}

	return base64.StdEncoding.EncodeToString(out), true
}

func GzipBase64Unmarshall(source string) (string, bool) {
	out, err := base64.StdEncoding.DecodeString(source)
	if err != nil {
		logs.Error(err)
		return "", false
	}

	fout := GzipUncompress(out)
	if fout == nil {
		return "", false
	}

	return string(fout), true
}
